import { useState, useEffect, useCallback } from 'react';
import { X, Play, Pause, Square, CheckCircle, Info, Settings2 } from 'lucide-react';
import { useAppDispatch, useAppSelector } from '@/store';
import { hideModal, showToast } from '@/store/slices/uiSlice';
import {
  processVideo,
  cancelProcess,
  setCurrentTask,
  startProgressSubscription,
  stopProgressSubscription,
  updateProgressData,
} from '@/store/slices/videoSlice';
import { videoService } from '@/services/video';
import { formatFileSize, formatDuration } from '@/utils/format';
import Button from '@/components/common/Button';
import ProgressBar from '@/components/common/ProgressBar';
import FileSelector from '@/components/common/FileSelector';
import './styles.less';

interface VideoToolModalProps {
  toolId: string;
}

interface LocalProcessOptions {
  format?: string;
  quality?: 'low' | 'medium' | 'high' | 'lossless';
  resolution?: string;
  bitrate?: number;
  frameRate?: number;
  audioCodec?: string;
  videoCodec?: string;
  customSettings?: Record<string, any>;
}

const TOOL_CONFIGS = {
  convert: {
    title: '视频格式转换',
    description: '将视频转换为不同格式',
    icon: Play,
    options: {
      format: ['mp4', 'avi', 'mov', 'mkv', 'webm'],
      quality: ['low', 'medium', 'high', 'lossless'],
    },
  },
  compress: {
    title: '视频压缩',
    description: '压缩视频文件大小',
    icon: Settings2,
    options: {
      quality: ['low', 'medium', 'high'],
      bitrate: [1000, 2000, 5000, 8000, 10000],
    },
  },
  trim: {
    title: '视频剪辑',
    description: '裁剪视频片段',
    icon: Square,
    options: {
      startTime: 0,
      endTime: 0,
      preserveQuality: true,
    },
  },
  'audio-extract': {
    title: '音频提取',
    description: '从视频中提取音频',
    icon: Play,
    options: {
      format: ['mp3', 'wav', 'aac', 'flac'],
      quality: ['low', 'medium', 'high'],
    },
  },
  thumbnail: {
    title: '缩略图生成',
    description: '生成视频缩略图',
    icon: Play,
    options: {
      count: [1, 3, 5, 10],
      size: ['small', 'medium', 'large'],
      timestamp: [10, 25, 50, 75], // percentage
    },
  },
  resize: {
    title: '分辨率调整',
    description: '调整视频分辨率',
    icon: Settings2,
    options: {
      resolution: ['720p', '1080p', '1440p', '4K'],
      aspectRatio: ['16:9', '4:3', '1:1', '9:16'],
    },
  },
  rotate: {
    title: '视频旋转',
    description: '旋转和翻转视频',
    icon: Play,
    options: {
      rotation: [90, 180, 270],
      flip: ['none', 'horizontal', 'vertical'],
    },
  },
};

export const VideoToolModal: React.FC<VideoToolModalProps> = ({ toolId }) => {
  const dispatch = useAppDispatch();
  const { currentTask, recentFiles } = useAppSelector(state => state.video);

  const [selectedFiles, setSelectedFiles] = useState<string[]>([]);
  const [outputPath, setOutputPath] = useState('');
  const [options, setOptions] = useState<LocalProcessOptions>({});
  const [isProcessing, setIsProcessing] = useState(false);
  const [processProgress, setProcessProgress] = useState(0);
  const [currentStep, setCurrentStep] = useState('准备中...');
  const [processResult, setProcessResult] = useState<any>(null);

  const toolConfig = TOOL_CONFIGS[toolId as keyof typeof TOOL_CONFIGS];

  // Progress monitoring
  const handleProgressUpdate = useCallback(
    (data: any) => {
      if (currentTask) {
        dispatch(
          updateProgressData({
            taskId: currentTask.id,
            progress: data,
          })
        );
        setProcessProgress(data.percentage);
        setCurrentStep(data.currentStep);
      }
    },
    [currentTask, dispatch]
  );

  useEffect(() => {
    // 监听处理进度
    if (currentTask && currentTask.type === toolId) {
      setIsProcessing(currentTask.status === 'processing');
      setProcessProgress(currentTask.progress?.percentage || 0);
      setCurrentStep(currentTask.progress?.currentPhase || '处理中...');

      // Start progress subscription if processing
      if (currentTask.status === 'processing') {
        const cleanup = videoService.createProgressSubscription(
          currentTask.id,
          handleProgressUpdate
        );
        dispatch(
          startProgressSubscription({
            taskId: currentTask.id,
            cleanup,
          })
        );
      }

      if (currentTask.status === 'completed') {
        setProcessResult(currentTask.result);
        setIsProcessing(false);
        dispatch(
          showToast({
            type: 'success',
            title: '处理完成',
            message: `${toolConfig.title}已完成`,
          })
        );
        // Stop progress subscription
        dispatch(stopProgressSubscription(currentTask.id));
      }

      if (currentTask.status === 'failed') {
        setIsProcessing(false);
        dispatch(
          showToast({
            type: 'error',
            title: '处理失败',
            message: currentTask.error?.message || '未知错误',
          })
        );
        // Stop progress subscription
        dispatch(stopProgressSubscription(currentTask.id));
      }

      if (currentTask.status === 'canceled') {
        setIsProcessing(false);
        setProcessProgress(0);
        dispatch(stopProgressSubscription(currentTask.id));
      }
    }
  }, [currentTask, toolId, toolConfig?.title, dispatch, handleProgressUpdate]);

  // Cleanup subscriptions on unmount
  useEffect(() => {
    return () => {
      if (currentTask) {
        dispatch(stopProgressSubscription(currentTask.id));
      }
    };
  }, [currentTask, dispatch]);

  const handleClose = () => {
    if (isProcessing) {
      dispatch(cancelProcess());
    }
    dispatch(hideModal('video-tool-modal'));
  };

  const handleFileSelect = (fileIds: string[]) => {
    setSelectedFiles(fileIds);
  };

  const handleOptionChange = (key: string, value: any) => {
    setOptions(prev => ({
      ...prev,
      [key]: value,
    }));
  };

  const handleStartProcess = async () => {
    if (selectedFiles.length === 0) {
      dispatch(
        showToast({
          type: 'error',
          title: '请选择文件',
          message: '请先选择要处理的视频文件',
        })
      );
      return;
    }

    const inputFile = recentFiles.find(f => selectedFiles.includes(f.id));
    if (!inputFile) {
      dispatch(
        showToast({
          type: 'error',
          title: '文件不存在',
          message: '所选文件不存在或已被删除',
        })
      );
      return;
    }

    try {
      setIsProcessing(true);
      setProcessProgress(0);
      setCurrentStep('初始化处理...');

      // 生成输出路径
      const outputDir = await videoService.getOutputDirectory();
      const extension = getOutputExtension(toolId, options);
      const outputFileName = `${inputFile.name.split('.')[0]}_${toolId}.${extension}`;
      const fullOutputPath = `${outputDir}/${outputFileName}`;

      setOutputPath(fullOutputPath);

      // 开始处理
      const task = await dispatch(
        processVideo({
          inputPath: inputFile.path,
          outputPath: fullOutputPath,
          options: {
            ...options,
            // 转换resolution字符串为Resolution对象
            resolution: options.resolution
              ? {
                  width: 1920,
                  height: 1080,
                }
              : undefined,
          },
        })
      ).unwrap();

      // Set as current task
      dispatch(setCurrentTask(task));
    } catch (error) {
      console.error('处理失败:', error);
      setIsProcessing(false);
    }
  };

  const handlePauseResume = () => {
    if (currentTask) {
      if (currentTask.status === 'processing') {
        videoService.pauseProcess(currentTask.id);
      } else if (currentTask.status === 'paused') {
        videoService.resumeProcess(currentTask.id);
      }
    }
  };

  const handleStop = () => {
    if (currentTask) {
      dispatch(cancelProcess());
      setIsProcessing(false);
      setProcessProgress(0);
    }
  };

  const getOutputExtension = (toolId: string, options: LocalProcessOptions): string => {
    switch (toolId) {
      case 'convert':
        return options.format || 'mp4';
      case 'audio-extract':
        return options.format || 'mp3';
      case 'thumbnail':
        return 'jpg';
      default:
        return 'mp4';
    }
  };

  const renderOptions = () => {
    if (!toolConfig.options) return null;

    return (
      <div className='video-tool-modal__options'>
        <h4>处理选项</h4>

        {Object.entries(toolConfig.options).map(([key, values]) => (
          <div key={key} className='video-tool-modal__option'>
            <label>{getOptionLabel(key)}</label>
            {Array.isArray(values) ? (
              <select
                value={(options[key as keyof LocalProcessOptions] as string) || ''}
                onChange={e => handleOptionChange(key, e.target.value)}
              >
                <option value=''>请选择</option>
                {values.map(value => (
                  <option key={value} value={value}>
                    {value}
                  </option>
                ))}
              </select>
            ) : (
              <input
                type='number'
                value={(options[key as keyof LocalProcessOptions] as string) || ''}
                onChange={e => handleOptionChange(key, Number(e.target.value))}
                placeholder={`输入${getOptionLabel(key)}`}
              />
            )}
          </div>
        ))}
      </div>
    );
  };

  const getOptionLabel = (key: string): string => {
    const labels: Record<string, string> = {
      format: '输出格式',
      quality: '质量等级',
      resolution: '分辨率',
      bitrate: '比特率 (kbps)',
      frameRate: '帧率',
      audioCodec: '音频编码',
      videoCodec: '视频编码',
      startTime: '开始时间 (秒)',
      endTime: '结束时间 (秒)',
      count: '缩略图数量',
      size: '尺寸',
      timestamp: '时间点 (%)',
      rotation: '旋转角度',
      flip: '翻转方式',
      aspectRatio: '宽高比',
    };
    return labels[key] || key;
  };

  const renderProcessingStatus = () => {
    if (!isProcessing && !processResult) return null;

    return (
      <div className='video-tool-modal__processing'>
        {isProcessing && (
          <>
            <div className='video-tool-modal__progress'>
              <div className='video-tool-modal__progress-info'>
                <span className='video-tool-modal__progress-text'>{currentStep}</span>
                <span className='video-tool-modal__progress-percent'>
                  {processProgress.toFixed(1)}%
                </span>
              </div>
              <ProgressBar progress={processProgress} />
            </div>

            <div className='video-tool-modal__controls'>
              <Button
                variant='secondary'
                icon={currentTask?.status === 'paused' ? <Play /> : <Pause />}
                onClick={handlePauseResume}
              >
                {currentTask?.status === 'paused' ? '继续' : '暂停'}
              </Button>
              <Button variant='danger' icon={<Square />} onClick={handleStop}>
                停止
              </Button>
            </div>
          </>
        )}

        {processResult && (
          <div className='video-tool-modal__result'>
            <div className='video-tool-modal__result-header'>
              <CheckCircle className='w-5 h-5 text-green-600' />
              <h4>处理完成</h4>
            </div>
            <div className='video-tool-modal__result-info'>
              <p>
                <strong>输出文件:</strong> {outputPath}
              </p>
              {processResult.fileSize && (
                <p>
                  <strong>文件大小:</strong> {formatFileSize(processResult.fileSize)}
                </p>
              )}
              {processResult.duration && (
                <p>
                  <strong>时长:</strong> {formatDuration(processResult.duration)}
                </p>
              )}
              {processResult.processingTime && (
                <p>
                  <strong>处理用时:</strong> {formatDuration(processResult.processingTime)}
                </p>
              )}
            </div>
          </div>
        )}
      </div>
    );
  };

  if (!toolConfig) {
    return (
      <div className='video-tool-modal'>
        <div className='video-tool-modal__header'>
          <h2>工具不存在</h2>
          <Button variant='secondary' icon={<X />} onClick={handleClose} />
        </div>
        <div className='video-tool-modal__content'>
          <p>请求的工具不存在</p>
        </div>
      </div>
    );
  }

  return (
    <div className='video-tool-modal'>
      <div className='video-tool-modal__header'>
        <div className='video-tool-modal__title'>
          <toolConfig.icon className='w-5 h-5' />
          <h2>{toolConfig.title}</h2>
        </div>
        <Button variant='secondary' icon={<X />} onClick={handleClose} />
      </div>

      <div className='video-tool-modal__content'>
        <div className='video-tool-modal__description'>
          <Info className='w-4 h-4' />
          <p>{toolConfig.description}</p>
        </div>

        <div className='video-tool-modal__section'>
          <h3>选择文件</h3>
          <FileSelector
            multiple={false}
            fileTypes={['video']}
            selectedFiles={selectedFiles}
            onFileSelect={handleFileSelect}
          />
        </div>

        {renderOptions()}

        {renderProcessingStatus()}

        <div className='video-tool-modal__actions'>
          <Button variant='secondary' onClick={handleClose}>
            取消
          </Button>
          <Button
            variant='primary'
            onClick={handleStartProcess}
            disabled={isProcessing || selectedFiles.length === 0}
          >
            开始处理
          </Button>
        </div>
      </div>
    </div>
  );
};

export default VideoToolModal;
